package com.wutoon.etl.service.impl;

import com.alibaba.fastjson.JSON;
import com.wutoon.etl.handler.DataTransferHandler;
import com.wutoon.etl.mapper.DataSourceManage;
import com.wutoon.etl.pojo.DataSourceDO;
import com.wutoon.etl.pojo.DataTransferTask;
import com.wutoon.etl.pojo.MapReduceShard;
import com.wutoon.etl.pojo.PowerJobResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author 武兴云/72176468
 * @version 1.0
 * @date 2023/11/13 4:23 PM
 * @description 运维服务
 */
@Service
@Slf4j
public class BusinessInspectionService {

    @Resource
    private DataSourceManage dataSourceManage;


    public PowerJobResult<?> collectData(MapReduceShard shard) {
        log.info("BusinessInspectionService collectData start, param:{}", JSON.toJSONString(shard));
        try {
            DataTransferTask task = JSON.parseObject(shard.getCustomParam().toJSONString(), DataTransferTask.class);
            // 校验参数
            if (task.getIncrease() == null || StringUtils.isEmpty(task.getTargetTable()) ||
                    StringUtils.isEmpty(task.getQuerySql()) || StringUtils.isEmpty(task.getTargetSql()) ||
                    StringUtils.isEmpty(task.getSourceCode()) || StringUtils.isEmpty(task.getTargetCode())) {
                return new PowerJobResult<>(false, "非法参数, 必填参数为空");
            }
            DataSourceDO dataSource = dataSourceManage.queryByCode(task.getSourceCode());
            DataSourceDO targetDataSource = dataSourceManage.queryByCode(task.getTargetCode());
            if (dataSource == null || targetDataSource == null) {
                return new PowerJobResult<>(false, "源端或目标端数据库不存在");
            }
            task.setDataSource(dataSource);
            task.setTargetSource(targetDataSource);

            DataTransferHandler handler = new DataTransferHandler(task);
            handler.start();
            log.info("BusinessInspectionService collectData end");
            return new PowerJobResult<>(true, shard);
        } catch (Exception e) {
            log.error("BusinessInspectionService collectData error:", e);
            return new PowerJobResult<>(false, e.getMessage());
        }
    }


}
